<template>
  <div class="user">
    <el-col :span="24">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
    <el-col :span="24" class="user-content">
      <!-- 输入框 -->
      <el-col :span="6">
        <el-col :span="18">
          <el-input placeholder="请输入用户名" prefix-icon="el-icon-search" v-model="searchInput"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="searchUser">搜索</el-button>
        </el-col>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="isShow = true">添加用户</el-button>
      </el-col>
      <el-col :span="24">
        <el-table :data="userList.users" border style="width: 100%">
          <el-table-column prop="id" label="id" width="140">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="140">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="200">
          </el-table-column>
          <el-table-column prop="create_time" label="电话" width="140">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="140">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="140">
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button type="primary" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="danger" @click="delUser(scope.row)">删除</el-button>
              <el-button type="info" @click="setRole(scope.row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="9" style="margin-top: 20px;">
        <div class="block">
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum"
              :page-sizes="[2, 4, 6, 8]" :page-size="100" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-col>
    <el-form label-width="100px" class="user-form" v-show="isShow" key="user-form">
      <!-- 标题 -->
      <p>添加用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="form.username"></el-input>
        <span>{{ form.usernameMsg }}</span>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" autocomplete="off" v-model="form.password"></el-input>
        <span>{{ form.passwordMsg }}</span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="form.email"></el-input>
        <span>{{ form.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="form.phone"></el-input>
        <span>{{ form.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">确认</el-button>
        <el-button @click="isShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-form label-width="100px" class="edit-form" key="edit-form" v-show="editIsShow">
      <!-- 标题 -->
      <p>编辑用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="editForm.username" :disabled="true"></el-input>
        <span></span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="editForm.email"></el-input>
        <span>{{ editForm.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="editForm.phone"></el-input>
        <span>{{ editForm.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editSubmission">确认</el-button>
        <el-button @click="editIsShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 权限设置弹出框 -->
    <el-dialog title="分配角色" :visible.sync="centerDialogVisible" width="30%" center style="line-height: 20px;">
      <el-form :model="form" ref="formRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="当前用户" prop="username">
          <el-input type="text" autocomplete="off" v-model="form.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="当前角色" prop="role_name">
          <el-input type="text" autocomplete="off" v-model="form.role_name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_name">
          <el-select v-model="role_name" placeholder="请选择角色">
            <el-option label="主管" value="30"></el-option>
            <el-option label="测试角色" value="31"></el-option>
            <el-option label="测试角色2" value="34"></el-option>
            <el-option label="超级管理员" value="-1"></el-option>
            <el-option label="test" value="40"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setRoleSubmission">确认</el-button>

          <el-button @click="centerDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 遮罩层 -->
    <div class="mask " v-show="isShow || editIsShow"></div>
  </div>
</template>

<script>
import axios from 'axios';
import http from '@/mixins/http.js'
export default {
  mixins: [http()],
  data:  { => (returnrus/rLisa: [],
    pagination: {
      pageSize: 2,
      c/ere{tPage:v1',
  },
cp  isAddDiglogVisible: false,
    seaechKeywo[d]z'' 2, h  isEditDialogVisible: false,
    selectedUserId: '',
    roleSelection: {
      roleId: '',
      roleName: ''
    },
      role_name: '',
      centerDialogVisible: false,
      total: 0,
      form: {
        id:   ''
        usern  am '',
          psword: '',
        email: '',
          one: '',
        us  ermeMsg: ''  ,       passwor  dM: '',
        e  maMsg: '',
        phoneMsg: '  '     },
      editForm: {  
      usern  am '',
        ema  il'',
        phon  e:',
        us  ermeMsg: '',
        emailMsg: '',
        phoneMsg: ''
        }
    }
  },
    crted() {
    t  hifetc  hUrData({
        pasize: this.pagesi  ze
      pagenum  : is.pagenum
      .then(data => {
       his.arr = data
      this.total =   da
a.t )   })  
  },
    mhods: {
    async fetc  hUsData(params = {}) {
       tr {
        const  re s= wait this.$htt pGet('/uers', params userList
      return res.data.data  
      } cch (error) {
        console.error('请求失败:', er ror)
         is.$message.error('数据加载失败')
        return null
     ;}
     ,
    handleSizC ha;nge(va) {
      con solel ocovthis.$haed条;E'请求失败 )
 ,sa用户gesie  =; vl 
     thisf  e;tcserD  ata {
      pagesize: this.pages  ize
        pagenum: this.p agenum
     }).then(dat a => {
       this.arr =  dat 
     })

    },
    h  andCurrentChange(val) {
        conle.log(`当前页: $ {val` );
     this.pa  gen = val  
      is.fetchUserData({userList       p  ageze: this.pagesize,
         pageum: this.pagenu m
     }).then(data => { 
        his.arr = data
        })
    },
    async addUser(  ) {      if (this  .fo.username.length < 3 |  | ts .f om.sername.length > 6) {  
      this.form.uuserListnameMsg = '用户名长度为3-6位'
        return
      } else {
        this.form.usernameMsg = ''
       }      if  (this.fom.pas swor. lengh < 6 || this.form.pass  worlength   > ) {
        this.form.passwordMsg = '密码长度为6-15位'
        return
       } ele {
        this.form.passwordMs  g ='
      }
      if (t  hisorm.email.length < 6 || this.form  .emil.lengh > 15) {

        this.form.emailMsg = '邮箱长度为6-15位'
          rern
      } else {
        this.form.emai  lMs= ' '
     }
       f  (ths.form.phone.length  !== 11)  {       this.form.phoneMsg = '手机号长度为11位'
        return
      } else {
         his.form.phon  eMs= '' 
      }
     try {
         const r s = awat   thi$httpPost('/users', this.form)
        let { data: { data, me  ta } = res
        if (meta.statu s ==  201){
          this.fetch  Useata({
            pagesize: this.p  ageze,
            page  numthis.pagenum
          }).then(data   =>
             thisarr =  dat
              ts.total = data.total
          })
           his .$mesage({
            me ssag: '添加成功',
             type 'success'
          })
           his.isShow = fal se
         
      } catch (error) {  
      console.error('请求失败:'  , eor)
        this.$message.error('数据加载  失败'
         return  ul l
      }

    },
      itUser(obj) {
      this.e  ditShow = true
      console.log(obj);
      this.editForm.use  rna = obj.username
       tis.form.id = obj.id
    },
     sync editSubmission() {
        conle.log(this.form.id);
      if (this.editForm.email.length < 6 || th is.ei tFor.email.length > 15) {
        thi s.edt Formema ilMsg = 邮箱长度为  6-1'
        return
      } else {  
       ths.editForm.emailMsg = ''
      }
       f (this.editForm.phone.length !== 11) {
         his  .edForm.phoneMsg =   '手长度为11位'
        return 
       } ee {
          th.editForm.phoneMsg = ''
      }
      try {
        const res = aw ait h is.$ttpPut('/users/' + this.form.id , ths .ediForm)
        let { da ta:  da ta, eta } } = res
        if (meta.status === 200) {
          th  is.tchUserData({
            pagesize: this.pagesize,
            pagenum : ths.p agenum
         }).then(dat a =>{
            this.arr   = ta
          })
          th  is.messge( {
           message: '  编辑成,
            type: 'succe  ss'          })
          this.editIsSho  w =alse
        }
      } c atch( erro) {
         co s oe.rror('请求async delUser(obj) {  this.ry {sa      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', { }        confirmButtonText: '确定', t        cancelButtonText: '取消',ir        type: 'warning',       })        this.id = obj.idex      const res = await this.$httpDelete('/users/' + this.id)'w      let { data: { data, meta } } = resbj      if (meta.status === 200) {th        this.fetchUserData({s.          pagesize: this.pagesize, m          pagenum: this.pagenumta        }).then(data => {            this.arr = data            this.total = data.total          }) p        this.$message({            type: 'success',            message: meta.msg          });s.      } =    } catch (error) {})      if (error === 'cancel') {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      } else {
        console.error('请求失败:', error)
        this.$message.error('数据加载失败')
      }
    }          message: '已  取消删
          });
          else {
          console.er ror('请求失:', error)
          this.$me ssage.eror('数据加载失败')
        }
      } 
    },
    setRole(obj)   {
    console.log(obj);
      this.cent  erDlo  gVible = true
      this.form.us  erne = obj.userna me
      ths.form.role_name   = j.role_nam  e
    this.role_id = obj.id
    },
    async setRoleSubmission() {
      t ry {
        const tempArray = {
           i:  thi.role_id,
          ri d: tis. rolename
          }
      const res = await this  .$hpPut('/use rs/'+ thi s.roe_id + '/ro  le'tempArray)
        let { data:   { ta, meta   } } res
        i  f (ta.status === 200 ) {          const roleMap = {
            '30': '主管',
            '31':   '测试',
             '3': '测 试角色2,
             '1':  '超级管理员'
            '40':   'te'
          };
          this.f  etcserData({
            pagesize:   th.pagesize,
            pagen um: h is. agenum          }).t hen(a ta = {
            this.arr =   da
          })
          this.$messag  e({             mes sag '改成功     async       type: 'su  cax.sy
     )heconstar  '=Aawaaohis.io$httpGek('/us=rs', {  },e
        }
      } ca tc (error) {
    InKeyword leerror('pa'..., erroe inatiom
        }e     .r});
数据加 pa')paguszrLiut = r s.data.data;} 
 }rcatch}(error)h{ser() })this $nandltErroreerros,'搜索失败');/us  er', { 
      headers: {
          'Authorization': this.token
        },
        params: {
          query: this.searchInput,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      }).then(res => {

      })
    }
  }
}
</script>

<style scoped lang="scss">
.user-content {
  margin: 20px;
  background-color: #fff;
  height: 800px;
  padding-left: 50px;

}

::v-deep .el-table__header thead tr th {
  height: 30px !important;
  line-height: 30px;
}

.user-form {
  width: 600px;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}

.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 3;
}

.edit-form {
  width: 600px;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}
</style>